package com.example.mediaplay;


import java.io.File;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.IBinder;
import android.view.SurfaceHolder;

public class MediaPlayerService extends Service {

	private IBinder binder = new MediaPlayperBinder();
	private MediaPlayer mediaPlayer;
	private String path;
	private int position;
	private SurfaceHolder sh;
	
	@Override
	public boolean onUnbind(Intent intent) {
		mediaPlayer.release();
		return super.onUnbind(intent);
	}

	@Override
	public IBinder onBind(Intent intent) {
		mediaPlayer = new MediaPlayer();
		return binder;
	}
	
	private void playService() {
		try {
			File file = new File(path);
			if (file.exists()) {
				mediaPlayer.reset();
				mediaPlayer.setDataSource(file.getAbsolutePath());
				mediaPlayer.setDisplay(sh);
				mediaPlayer.prepare();
				mediaPlayer.setOnPreparedListener(new MediaPlayerOnPreparedListener(
						position));
				position = 0;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	private void pauseService(){
		if(mediaPlayer.isPlaying()){
			mediaPlayer.pause();
			position = mediaPlayer.getCurrentPosition();
		}
	}
	
	private void stopService(){
		if(mediaPlayer.isPlaying()){
			mediaPlayer.stop();
		}
	}
	
	private void setPathService(String path){
		this.path = path;
	}
	
	private void setSHService(SurfaceHolder sh){
		this.sh = sh;
	}
	
	private final class MediaPlayerOnPreparedListener implements OnPreparedListener{

		private int position;
		
		public MediaPlayerOnPreparedListener(int position) {
			this.position = position;
		}


		@Override
		public void onPrepared(MediaPlayer mp) {
			mediaPlayer.start();
			if(position>0){
				mediaPlayer.seekTo(position);
			}
		}
		
	}


	
	
	private final class MediaPlayperBinder extends Binder implements IMediaPlayer{
		@Override
		public void play(){
			playService();
		}
		
		@Override
		public void pause(){
			pauseService();
		}
		
		@Override
		public void stop(){
			stopService();
		}
		
		@Override
		public void setPath(String path){
			setPathService(path);
		}
		
		@Override
		public void setSurfaceHolder(SurfaceHolder sh){
			setSHService(sh);
		}
	}

}
